#include <net/if.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <sys/types.h>
#include <linux/if_tun.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

static int tun_fd;
static char* dev;

#define CLEAR(x) memset(&(x), 0, sizeof(x))

static int tun_alloc(char *dev)
{
    struct ifreq ifr;
    int fd, err;

    if( (fd = open("/dev/net/tun", O_RDWR)) < 0 ) {
        perror("Cannot open TUN/TAP dev\n"
                    "Make sure one exists with " 
                    "'$ mknod /dev/net/tap c 10 200'");
        exit(1);
    }

    CLEAR(ifr);

    /* Flags: IFF_TUN   - TUN device (no Ethernet headers)
     *        IFF_TAP   - TAP device
     *
     *        IFF_NO_PI - Do not provide packet information
     */
    ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
    if( *dev ) {
        strncpy(ifr.ifr_name, dev, IFNAMSIZ);
    }

    if( (err = ioctl(fd, TUNSETIFF, (void *) &ifr)) < 0 ){
        perror("ERR: Could not ioctl tun");
        close(fd);
        return err;
    }

    strcpy(dev, ifr.ifr_name);
    return fd;
}

int main()
{
    int nread;
    char buffer[1500];

    dev = calloc(10, 1);
    tun_fd = tun_alloc(dev);

    if(tun_fd < 0){
        printf("error!!");
        exit(1);
    } 

    while(1){
        nread = read(tun_fd,buffer,sizeof(buffer));
        if(nread < 0){
            printf("error!!");
            exit(1);
        }
        printf("Read %d bytes from tun/tap device\n",nread);
    }

    return 0;
}